﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using PhiStore.Threading;

namespace FileSystemAnalysis.Code
{
    internal class IntermediateConsumer : Boostable
    {
        private Model model;
        private Channel<ResultCapsule> inputChannel;
        private Channel<string> outputChannel;
        private Dictionary<ulong, List<string>> files;

        private ulong filesIndexed = 0L;

        public IntermediateConsumer(Model model, Channel<ResultCapsule> inputChannel, Channel<string> outputChannel)
        {
            this.model = model;
            this.inputChannel = inputChannel;
            this.outputChannel = outputChannel;
            this.files = new Dictionary<ulong, List<string>>();
        }

        public void Run()
        {
            try
            {
                while (true)
                {
                    ResultCapsule res = inputChannel.Receive();
                    if (!files.ContainsKey(res.size))
                        files.Add(res.size, new List<string>());

                    files[res.size].Add(res.path);

                    model.FilesIndexed = filesIndexed++;
                }
            }
            catch (PoisonException)
            {
               //all files indexed
            }
            try
            {
                model.Shaing = true;
                foreach (List<string> equalsizedFiles in files.Values)
                {
                    if (equalsizedFiles.Count > 1)
                        foreach (string file in equalsizedFiles)
                        {
                            outputChannel.Send(file);
                            model.SentForSha++;
                        }
                }
            }
            catch (PoisonException)
            {

            }
            outputChannel.Poison();

        }
    }
}
